﻿'''
Author: duliang 
Date: 2024-1-25 16:07:35
LastEditors: duliang thinktanker@163.com
LastEditTime: 2024-07-21 10:37:28
FilePath: \sajj\localORC.py
Description: 截屏识别，串口发送给esp32c3，转发服务器
'''
import time
import numpy as np
from mySerial import getCOMport, openCOM
import ctypes
# import bz2
import zlib
from paddleocr import PaddleOCR
from llj_snapshot import snapshot, cutTable, markpic
import re
from getData import *
# from shortcontent import shortcontent

ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 6)
TIME_FLAG = 300
TIME_NET = 3720
station = 1  #1是一站，2是二站
if station == 1:
    className = "ctDSP"
    winName = "运行报表"  #修改
elif station == 2:
    className = "ViewPU"
    winName = "刘老涧二站实时报表页面"
ocr = PaddleOCR(
    use_angle_cls=False,
    use_gpu=False,
    rec_model_dir=r".\whl\rec\ch\ch_PP-OCRv4_rec_infer",
    det_model_dir=r".\whl\det\ch\ch_PP-OCRv4_det_infer",
    cls_model_dir=r".\whl\cls\ch_ppocr_mobile_v2.0_cls_infer",
)


def getOCRtext(image):
    '''
    飞桨识别文字
    '''
    img_convert_ndarray = np.array(image)
    t = time.time()
    ocr_text = ocr.ocr(
        img=img_convert_ndarray,
        #   det=False,
        #   rec=False,
        cls=False)
    print(time.time() - t)
    return ocr_text


def compress_string(string: str):
    # compressed_data = bz2.compress(bytes(string, 'utf-8'))
    compressed_data = zlib.compress(bytes(string, 'utf-8'))
    return compressed_data


if __name__ == "__main__":

    while 1:
        com_port = getCOMport('USB-Enhanced-SERIAL CH343')  #正式用
        #print(com_port)
        # com_port = "COM11"  #测试用
        while com_port:
            if (int(time.time()) - 6) % TIME_NET == 0:
                print('发送数据库数据')
                cyg_data = get_data(10)
                sendContent = tosendcontent(cyg_data)
                time.sleep(1)
            elif int(time.time()) % TIME_FLAG == 0:
                try:
                    results = []
                    if snapshot(className=className, winName=winName):  #正式用
                        # cut_paths, cut_images = cutpic("./pil.jpg")  #正式用
                        cut_paths, cut_images = cutTable("./pil.jpg",
                                                         station)  #正式用
                        for index, img in enumerate(cut_images):
                            if not "warn" in cut_paths[index]:
                                results.append(getOCRtext(img))
                        for index, r in enumerate(results):
                            markpic(f'./image/{cut_paths[index]}.jpg',
                                    resultlist=r)
                        # 发送的内容
                        sendContent = ''
                        for result in results:
                            for t0 in result:
                                for t1 in t0:
                                    sendContent += ' ' + str(t1[-1][0])
                        sendContent = sendContent.replace('. ', '.').replace(
                            '。', '0')
                        patten = r'35kV|6kV|1#|2#|3#|4#|m3|：|10m|m|10m²|10\*|[^-\d.]'
                        sendContent = re.sub(patten, ' ', sendContent)
                        # 多余2个空格转成1个空格
                        sendContent = re.sub(r' {2,}', ' ', sendContent)
                        # 正常应该195个数
                        print(len(sendContent), sendContent)
                    else:
                        sendContent = '窗口未找到'
                        time.sleep(10)
                except Exception as e:
                    sendContent = str(e)
                    print(e)
                    # 压缩
            else:
                print(int(time.time()) % TIME_FLAG, end='\r')
                time.sleep(1)
                continue
            sendContent = compress_string(sendContent) + b'END'
            try:
                openCOM(comport=com_port, sendContent=sendContent)
            except Exception as e:
                print(e)
                break
        time.sleep(1)
